package com.da.javatest.thread.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/12 11:30
 * @description
 */
public class CountDownLatch2 {
    public static class MyThread extends Thread {
        private int runningTime;
        private CountDownLatch countDown;
        private CountDownLatch wait;

        public MyThread(String name, int runningTime, CountDownLatch countDown, CountDownLatch wait) {
            super(name);
            this.runningTime = runningTime;
            this.countDown = countDown;
            this.wait = wait;
        }

        @Override
        public void run() {
            // 全体等待
            try {
                wait.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread thread = Thread.currentThread();
            long startTime = System.currentTimeMillis();
            System.out.println(thread.getName() + "准备开始起跑");
            try {
                TimeUnit.SECONDS.sleep(runningTime);
            } catch (InterruptedException e) {

            } finally {
                countDown.countDown();
            }
            long endTime = System.currentTimeMillis();
            System.out.println(thread.getName() + "跑步完成，耗时：" + (startTime - endTime));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "线程 start!");
        CountDownLatch wait = new CountDownLatch(1);
        CountDownLatch countDown = new CountDownLatch(3);

        long startTime = System.currentTimeMillis();
        new MyThread("小张", 3, countDown, wait).start();
        new MyThread("小雷", 5, countDown, wait).start();
        new MyThread("小陈", 2, countDown, wait).start();
        // 准备时间
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + ",枪响了，大家开始跑");
        wait.countDown();

        countDown.await();
        long endTime = System.currentTimeMillis();

        System.out.println(Thread.currentThread().getName() + "所有人跑完了，主线程耗时：" + (startTime - endTime));
    }
}
